<?php
set_include_path('system'.PATH_SEPARATOR.'templates');

require_once('Template.php');
require_once('RedirectBrowserException.php');
require_once('DatabaseUtility.php');
require_once('CustomFunctions.php');

$tmpl = new Template();

$id = $_GET['id'];
$pnrseq = $_GET['pnrseq'];
$pro = $_GET['pro'];
$loc = $_GET['loc'];
$ref = $_GET['ref'];

$getref = "";
if (!empty($ref)) {
	$q = " AND mass.dataSource=$ref";
	$query .= $q;
	$getref = "&ref=$ref";
}

$queryDs = "SELECT reference,dataSource.id FROM peptide,mass,dataSource WHERE peptide.mass=mass.id AND mass.dataSource=dataSource.id AND ";
$query = "SELECT peptide.id,peptide.location,peptide.sequence,mass.id as msid,mass.file,mass.scan,ISNULL(mass.mz) AS nullMass,dataSource.reference,dataSource.link,protein.id AS pid,protein.annotation,organism.latin,organism.commonName ".
	"FROM peptide,mass,dataSource,protein,organism WHERE peptide.mass=mass.id AND peptide.protein=protein.id AND mass.dataSource=dataSource.id AND protein.organism=organism.label AND ";
if(!empty($id)) {
	$q= 'peptide.id='.$id;
	$query .= $q;
	$queryDs .= $q;
} elseif (!empty($pnrseq)) {
	$q = "peptide.phosphoSequence='$pnrseq' AND peptide.protein=$pro AND peptide.location=$loc";
	$query .= $q;
	$queryDs .= $q;
} else {
	// TODO
	// Display error message Phosphosite information not available!
}

openDatabase();

$query .= " ORDER BY mass.id";

$rows = runQuery($query);
if (!empty($rows[0])) {
	$seqpep = $rows[0]['sequence'];
	$seq = formatpep($seqpep,$rows[0]['id'],$getref, true);
	$phosphosites = getptms($rows[0]['id']);
	$org = $rows[0]['latin'].' ('.$rows[0]['commonName'].')';
	$loc = $rows[0]['location'];
}

$ms = array();
$params = array();
$headers = array();
foreach($rows as $row) {
	if (isset($row['scan'])) {
		$mshtml = "{$row['file']}.{$row['scan']}";
	} else {
		$mshtml = $row['msid'];
	}

	if ($row['nullMass']==0) {
		$mshtml = "<a href=\"spectrum/view_spectrum.php?msid={$row['msid']}&pep={$row['id']}\" target=\"_blank\">$mshtml</a>&nbsp;&nbsp;";
	}

	$ms[$row['msid']] ++;
	$msheader[$row['msid']] = $mshtml;

	$link = $row['link'];
	if (empty($link)) {
		$param['Reference'] = $row['reference'];
	} else {
		$param['Reference'] = "<a href=\"{$link}\" target=\"_blank\">{$row['reference']}</a>";
	}
	$headers['Reference'] = 1;

	$query = "SELECT value,peptideParameterType.name FROM peptideParameter,peptideParameterType WHERE peptide='{$row['id']}' AND peptideParameter.parameter=peptideParameterType.id";
	$res1 = runQuery($query);
	foreach($res1 as $row1) {
		$param[$row1['name']] = $row1['value'];
		$headers[$row1['name']] = 1;
	}

	$params[] = $param;
}

// query for datasources
$result = runQuery($queryDs);
foreach($result as $row) {
	$dataSource[$row['id']] = $row['reference'];
}
if (count($dataSource)>1) {
	$dataSource[0] = "All";
	ksort($dataSource);
}

$i = 0;
$spectrumData = array();
foreach ($ms as $msid=>$mscount) {
	$spectrumData[] = array(
		'mp'		=> merge_params(array_slice($params, $i, $mscount)),
		'msid' 		=> $msid
	);
	$i += $mscount;
}

foreach($phosphosites as $row) {
	$sites[] = array(
		'locationInProtein' => $row['locationInProtein'], 
		'id' 				=> $row['site'], 
		'amino' 			=> substr(preg_replace('/[^a-zA-Z]/', '', $pnrseq), $row['locationInPeptide'], 1)
	);
}

// reference links
$refs = array();
$query ="SELECT id,link,reference FROM dataSource ORDER BY pubmed DESC;";
$result = runQuery($query);
foreach($result as $row) {
	$refID = $row['id'];
	$link = $row['link'];
	if (empty($link)) {
			$refs[$refID] = $row['reference'];
	} else {
			$refs[$refID] = $link;
	}
}
if(!empty($ref)) $refLink = $refs[$ref];
else if (count($dataSource) == 1) {
	$refID = array_keys($dataSource);
	$refLink = $refs[$refID[0]];
}

$tmpl->headers		= $headers;
$tmpl->msheader		= $msheader;
$tmpl->id			= $id;
$tmpl->pnrseq		= $pnrseq;
$tmpl->pro			= $pro;
$tmpl->loc 			= $loc;
$tmpl->spectrumData	= $spectrumData;
$tmpl->sites		= $sites;
$tmpl->ms			= $ms;
$tmpl->numSpectra 	= count($ms);
$tmpl->seq 			= $seq;
$tmpl->ref			= $ref;
$tmpl->refLink		= $refLink;
$tmpl->dataSource 	= $dataSource;
$tmpl->protLink		= 'protein.php?id='.$pro.$getref;
$tmpl->accessions 	= getXrefLink($pro);
$tmpl->description 	= $rows[0]['annotation'];
$tmpl->organism 	= '<i>'.$rows[0]['latin'].'</i> ('.$rows[0]['commonName'].')';
$tmpl->current 		= 'browse';
$tmpl->pageContent 	= $tmpl->build('peptide.tmpl');

closeDatabase();

print $tmpl->build('page.tmpl');

function formatpep($seqpep,$id,$getref,$bSeq) {
	$phosphosites = array();
	$seq = "";
	$sites = getptms($id);

	$start = 0;
	foreach($sites as $site) {
		$loc = $site['locationInPeptide'];
		$href = 'href="phosphosite.php?id='.$site['site'].$getref.'"';
		$sbst = '<a class="ui-corner-all phosphosite" '.$href.'>'.substr($seqpep,$loc,1).'</a>';
		$seq = $seq.substr($seqpep,$start,$loc-$start).$sbst;
		$start = $loc + 1;
		
		$phosphosites[$href] = substr($seqpep,$loc,1);
	}
	$seq = $seq.substr($seqpep,$start);
	
	if($bSeq) {
		return $seq;
	} else {
		return $phosphosites;
	}
}

function getptms($id) {
	$query_getsites = "SELECT site,ptm,locationInPeptide,locationInProtein FROM peptideSiteRelation,site WHERE peptide=$id AND peptideSiteRelation.site=site.id ORDER BY locationInPeptide";
	
	$result_getsites = runQuery($query_getsites);

	$sites = array();
	foreach($result_getsites as $row_getsites) {
		$sites[] = $row_getsites;
	}

	return $sites;
}

function merge_params($params) {
	if (count($params)<=1)
		return $params;

	$keep[] = array();
	$n = count($params);
	for ($i=0; $i<$n; $i++) {
		$parami = $params[$i];
		$keep[$i] = true;
		for ($j=0; $j<$i; $j++) {
			if ($keep[$j]) {
				$paramj = $params[$j];
				// find the intersection of two arrays
				$intersect = array_intersect_assoc($parami,$paramj);
				// if the new param is equal or contained in an existing param
				if (count($intersect)==count($parami)) {
					$keep[$i] = false;
					break;
				} elseif (count($intersect)==count($paramj)) {
					// if the existing param is contained in the new param
					$keep[$j] = false;
					break;
				}
			}
		}
	}

	$ret = array();
	for ($i=0; $i<$n; $i++) {
		if ($keep[$i]) {
			$ret[] = $params[$i];
		}
	}

	return $ret;
}
?>